<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API测试页面（带认证）</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .test-section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; }
        .test-button { padding: 10px 15px; margin: 5px; background: #007bff; color: white; border: none; border-radius: 3px; cursor: pointer; }
        .test-button:hover { background: #0056b3; }
        .test-button:disabled { background: #6c757d; cursor: not-allowed; }
        .result { margin-top: 10px; padding: 10px; background: #f8f9fa; border-radius: 3px; white-space: pre-wrap; }
        .success { background: #d4edda; color: #155724; }
        .error { background: #f8d7da; color: #721c24; }
        .login-form { background: #e9ecef; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
        .form-group { margin: 10px 0; }
        .form-group label { display: block; margin-bottom: 5px; }
        .form-group input { width: 200px; padding: 5px; border: 1px solid #ccc; border-radius: 3px; }
        .status { padding: 10px; margin: 10px 0; border-radius: 3px; }
        .status.logged-in { background: #d4edda; color: #155724; }
        .status.logged-out { background: #f8d7da; color: #721c24; }
    </style>
</head>
<body>
    <h1>任务安排API测试页面（带认证）</h1>
    
    <!-- 登录表单 -->
    <div class="login-form">
        <h3>登录认证</h3>
        <div class="form-group">
            <label for="username">用户名:</label>
            <input type="text" id="username" value="admin" placeholder="请输入用户名">
        </div>
        <div class="form-group">
            <label for="password">密码:</label>
            <input type="password" id="password" value="admin123" placeholder="请输入密码">
        </div>
        <button class="test-button" onclick="login()">登录</button>
        <button class="test-button" onclick="logout()">退出登录</button>
        <div id="loginStatus" class="status logged-out">未登录</div>
    </div>
    
    <div class="test-section">
        <h3>1. 测试获取任务列表</h3>
        <button class="test-button" onclick="testGetList()" id="btnGetList" disabled>获取任务列表</button>
        <div id="listResult" class="result"></div>
    </div>
    
    <div class="test-section">
        <h3>2. 测试获取老人列表</h3>
        <button class="test-button" onclick="testGetElderly()" id="btnGetElderly" disabled>获取老人列表</button>
        <div id="elderlyResult" class="result"></div>
    </div>
    
    <div class="test-section">
        <h3>3. 测试获取护理项目列表</h3>
        <button class="test-button" onclick="testGetItems()" id="btnGetItems" disabled>获取护理项目列表</button>
        <div id="itemsResult" class="result"></div>
    </div>
    
    <div class="test-section">
        <h3>4. 测试获取用户列表</h3>
        <button class="test-button" onclick="testGetUsers()" id="btnGetUsers" disabled>获取用户列表</button>
        <div id="usersResult" class="result"></div>
    </div>

    <div class="test-section">
        <h3>5. 测试任务安排相关接口</h3>
        <button class="test-button" onclick="testTaskArrangement()" id="btnTaskArrangement" disabled>测试任务安排接口</button>
        <div id="taskResult" class="result"></div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8080';
        let authToken = localStorage.getItem('authToken');
        let isLoggedIn = !!authToken;
        
        // 页面加载时检查登录状态
        window.onload = function() {
            updateLoginStatus();
            updateButtonStates();
        };
        
        function updateLoginStatus() {
            const statusDiv = document.getElementById('loginStatus');
            if (isLoggedIn) {
                statusDiv.textContent = '已登录';
                statusDiv.className = 'status logged-in';
            } else {
                statusDiv.textContent = '未登录';
                statusDiv.className = 'status logged-out';
            }
        }
        
        function updateButtonStates() {
            const buttons = ['btnGetList', 'btnGetElderly', 'btnGetItems', 'btnGetUsers', 'btnTaskArrangement'];
            buttons.forEach(btnId => {
                const btn = document.getElementById(btnId);
                if (btn) {
                    btn.disabled = !isLoggedIn;
                }
            });
        }
        
        async function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }
            
            try {
                // 先获取验证码
                const captchaResponse = await fetch(`${API_BASE}/captchaImage`);
                const captchaData = await captchaResponse.json();
                
                if (captchaData.code !== 200) {
                    alert('获取验证码失败：' + captchaData.msg);
                    return;
                }
                
                // 使用验证码登录
                const response = await fetch(`${API_BASE}/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: username,
                        password: password,
                        code: '1234', // 简化测试，使用固定验证码
                        uuid: captchaData.uuid
                    })
                });
                
                const data = await response.json();
                
                if (data.code === 200 && data.token) {
                    authToken = data.token;
                    localStorage.setItem('authToken', authToken);
                    isLoggedIn = true;
                    updateLoginStatus();
                    updateButtonStates();
                    alert('登录成功！');
                } else {
                    alert('登录失败：' + (data.msg || '未知错误'));
                }
            } catch (error) {
                alert('登录请求失败：' + error.message);
            }
        }
        
        function logout() {
            authToken = null;
            localStorage.removeItem('authToken');
            isLoggedIn = false;
            updateLoginStatus();
            updateButtonStates();
            alert('已退出登录');
        }
        
        async function makeRequest(url, options = {}) {
            if (!isLoggedIn) {
                throw new Error('请先登录');
            }
            
            try {
                const response = await fetch(url, {
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + authToken,
                        ...options.headers
                    },
                    ...options
                });
                
                if (response.status === 401) {
                    // Token过期，清除本地存储
                    logout();
                    throw new Error('认证失败，请重新登录');
                }
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                return await response.json();
            } catch (error) {
                console.error('Request failed:', error);
                throw error;
            }
        }
        
        async function testGetList() {
            const resultDiv = document.getElementById('listResult');
            resultDiv.textContent = '正在请求...';
            
            try {
                const data = await makeRequest(`${API_BASE}/system/arrangement/joinList?pageNum=1&pageSize=10`);
                resultDiv.textContent = `成功获取任务列表:\n${JSON.stringify(data, null, 2)}`;
                resultDiv.className = 'result success';
            } catch (error) {
                resultDiv.textContent = `获取任务列表失败: ${error.message}`;
                resultDiv.className = 'result error';
            }
        }
        
        async function testGetElderly() {
            const resultDiv = document.getElementById('elderlyResult');
            resultDiv.textContent = '正在请求...';
            
            try {
                const data = await makeRequest(`${API_BASE}/system/elderly/list?pageNum=1&pageSize=10`);
                resultDiv.textContent = `成功获取老人列表:\n${JSON.stringify(data, null, 2)}`;
                resultDiv.className = 'result success';
            } catch (error) {
                resultDiv.textContent = `获取老人列表失败: ${error.message}`;
                resultDiv.className = 'result error';
            }
        }
        
        async function testGetItems() {
            const resultDiv = document.getElementById('itemsResult');
            resultDiv.textContent = '正在请求...';
            
            try {
                const data = await makeRequest(`${API_BASE}/system/item/list?pageNum=1&pageSize=10`);
                resultDiv.textContent = `成功获取护理项目列表:\n${JSON.stringify(data, null, 2)}`;
                resultDiv.className = 'result success';
            } catch (error) {
                resultDiv.textContent = `获取护理项目列表失败: ${error.message}`;
                resultDiv.className = 'result error';
            }
        }
        
        async function testGetUsers() {
            const resultDiv = document.getElementById('usersResult');
            resultDiv.textContent = '正在请求...';
            
            try {
                const data = await makeRequest(`${API_BASE}/system/user/list?pageNum=1&pageSize=10`);
                resultDiv.textContent = `成功获取用户列表:\n${JSON.stringify(data, null, 2)}`;
                resultDiv.className = 'result success';
            } catch (error) {
                resultDiv.textContent = `获取用户列表失败: ${error.message}`;
                resultDiv.className = 'result error';
            }
        }
        
        async function testTaskArrangement() {
            const resultDiv = document.getElementById('taskResult');
            resultDiv.textContent = '正在测试任务安排相关接口...';
            
            try {
                // 测试获取任务列表
                const listData = await makeRequest(`${API_BASE}/system/arrangement/joinList?pageNum=1&pageSize=5`);
                
                // 测试获取任务详情（如果有数据的话）
                let detailData = null;
                if (listData.rows && listData.rows.length > 0) {
                    const firstTaskId = listData.rows[0].id;
                    detailData = await makeRequest(`${API_BASE}/system/arrangement/detail/${firstTaskId}`);
                }
                
                resultDiv.textContent = `任务安排接口测试成功:\n\n任务列表:\n${JSON.stringify(listData, null, 2)}\n\n任务详情:\n${JSON.stringify(detailData, null, 2)}`;
                resultDiv.className = 'result success';
            } catch (error) {
                resultDiv.textContent = `任务安排接口测试失败: ${error.message}`;
                resultDiv.className = 'result error';
            }
        }
    </script>
</body>
</html>
